package net.googlecode.kharchenko.controllers;

import net.googlecode.kharchenko.domains.Person;
import net.googlecode.kharchenko.helpers.FileHelper;
import net.googlecode.kharchenko.helpers.impl.FileHelperImpl;
import net.googlecode.kharchenko.services.PersonService;
import net.googlecode.kharchenko.services.SecurityService;
import net.googlecode.kharchenko.validation.RegistrationValidation;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;


/**
 * Controller for page where user can change
 * his personal information.
 */
@Controller
public class EditUserDetailsController {


    @Autowired
    private RegistrationValidation registrationValidation;
    @Autowired
    private PersonService personService;
    @Autowired
    private SecurityService ss;
    private FileHelper fs = new FileHelperImpl();


    protected static final Logger logger = Logger.getLogger(EditUserDetailsController.class);

    /**
     * Return's change user info page
     *
     * @param model map with parameters, that send to view
     * @return change user info page
     */
    @RequestMapping(method = RequestMethod.GET, value = "/details")
    public String showEditDetails(Map model) {
        logger.info("Get current user");
        Person prs = personService.getPerson(ss.getCurrentUser());
        model.put("person", prs);
        model.put("groupList", personService.getAllGroups());
        model.put("current", "t1");
        logger.info("Return change info form");
        return "changeinfo";
    }

    /**
     * Change personal user information.
     *
     * @param person person with ne personal information
     * @param result errors
     * @param model  map with parameters, that send to view
     * @param file   file with user's avatar
     * @return change user info page if there are errors,
     *         else return succesfull change info page.
     */
    @RequestMapping(method = RequestMethod.POST, value = "/details")
    public String processEdit(HttpServletRequest request, Person person,
                              BindingResult result, Map model,
                              @RequestParam("avatar") MultipartFile file) {

        logger.info("Validate input information");
        registrationValidation.validateChangeInfoForm(person, result);
        String ext = registrationValidation.validateImageUrl(file.getOriginalFilename(), file.getSize(), result);
        logger.info("Extension of file is " + ext);
        if (result.hasErrors()) {
            model.put("groupList", personService.getAllGroups());
            return "changeinfo";
        }
        person.setGroup(personService.getGroup(person.getGroup().getId()));


        if (file.getSize() > 0) {

            person.setImgurl(person.getId().toString() + ext);
            String filename = request.getRealPath("") + "userimg\\" + person.getImgurl();
            logger.info(filename);
            try {
                fs.copyFile(file, filename);
            } catch (IOException e) {
                logger.info(e);

            }
        }
        logger.info("Update person information");
        personService.updatePersonInfo(ss.getCurrentUser(), person);

        return "changesuccess";
    }


    /**
     * Change user's password.
     *
     * @param person person with ne personal information
     * @param result errors
     * @param model  map with parameters, that send to view
     * @return change user info page if there are errors,
     *         else return succesfull change info page.
     */
    @RequestMapping(method = RequestMethod.POST, value = "/changepass")
    public String processChangePassword(Person person,
                                        BindingResult result, Map model,
                                        @RequestParam("confirmpassword") String confirmPass) throws IOException {

        registrationValidation.validatePassword(person, result);
        registrationValidation.validateConfirm(person.getPassword(), confirmPass, result);

        if (result.hasErrors()) {
            model.put("groupList", personService.getAllGroups());
            model.put("current", "t2");
            Person prs = personService.getPerson(ss.getCurrentUser());
            person.setFname(prs.getFname());
            person.setSname(prs.getSname());
            person.setTname(prs.getTname());
            person.setGroup(prs.getGroup());
            person.setImgurl(prs.getImgurl());
            return "changeinfo";
        }


        personService.changePassword(ss.getCurrentUser(), person.getPassword());


        return "changesuccess";
    }


}
